package com.ice.framework.web.config;

import cn.hutool.core.io.FileUtil;
import com.ice.framework.web.config.properties.SpringMultipartProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;

import javax.servlet.MultipartConfigElement;
import java.io.File;

/**
 * 文件上传配置
 * @author wangwei
 * @Date 2022/1/4 10:13
 */
@Configuration
@EnableConfigurationProperties(value = {SpringMultipartProperties.class})
public class SpringMultipartConfig {

    /**
     * 文件上传配置
     * @Author wangwei
     * @Date 2022/1/4
     */
    @Bean
    public MultipartConfigElement multipartConfigElement(SpringMultipartProperties properties) {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //单个文件最大
        factory.setMaxFileSize(DataSize.ofBytes(properties.getMaxFileSize()));
        /// 设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.ofBytes(properties.getMaxRequestSize()));
        //设置临时文件夹（tomcat启动时会在/tmp下自动创建临时文件夹，但长时间不使用会被linux删除掉）
        File tmp = FileUtil.mkdir("tmp");
        factory.setLocation(tmp.getAbsolutePath());
        return factory.createMultipartConfig();
    }
}
